﻿using System;
using System.Web;
using com.pro2e.console.core.hibernate;
using NHibernate.Context;
using com.pro2e.web.config.init;
using NHibernate;

/// <summary>
/// CurrentSessionModule 的摘要描述
/// </summary>
/// 
namespace com.pro2e.web.config
{
    public class CurrentSessionModule : IHttpModule
    {
        log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public void Init(HttpApplication application)
        {
            application.BeginRequest += new EventHandler(Application_BeginRequest);
            application.EndRequest += new EventHandler(Application_EndRequest);
        }

        public void Dispose()
        {

        }

        private void Application_BeginRequest(object sender, EventArgs e)
        {
            //NHibernateHelper.BeginTransaction();            
            ISession session = NHibernateSessionManager.Instance.GetSession();
            ITransaction ix = session.BeginTransaction();         
            HttpContext.Current.Items["ITransaction"] = ix;                     
        }

        private void Application_EndRequest(object sender, EventArgs e)
        {
           // NHibernateHelper.Commit();            
            try
            {
                
                ISession session = NHibernateSessionManager.Instance.GetSession();

                if (session.Transaction.IsActive)
                {
                    session.Flush();
                    session.Transaction.Commit();
                }
            }
            catch (Exception ex)
            {
                ISession session = NHibernateSessionManager.Instance.GetSession();
                log.Error(ex);
                session.Transaction.Rollback();
            }
            finally
            {
                NHibernateSessionManager.Instance.GetSession().Close();
            }
            
        }
    }
}